//
//  NSMutableDictionary+Safe.m
//  ICome
//
//  Created by zhangrongwu on 2017/4/18.
//  Copyright © 2017年 iCom. All rights reserved.
//

#import "NSMutableDictionary+Safe.h"
#import "NSObject+Extension.h"
#import <objc/runtime.h>

@implementation NSMutableDictionary (Safe)
+ (void)load {
    //只执行一次这个方法
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        // 替换 removeObjectForKey:
        NSString *tmpRemoveStr = @"removeObjectForKey:";
        NSString *tmpSafeRemoveStr = @"safeMutable_removeObjectForKey:";
        
        [NSObject swizzleInstanceMethod:NSClassFromString(@"__NSDictionaryM")
                         originSelector:NSSelectorFromString(tmpRemoveStr)
                          otherSelector:NSSelectorFromString(tmpSafeRemoveStr)];
        
        
        
        // 替换 setObject:forKey:
        NSString *tmpSetStr = @"setObject:forKey:";
        NSString *tmpSafeSetRemoveStr = @"safeMutable_setObject:forKey:";
        
        [NSObject swizzleInstanceMethod:NSClassFromString(@"__NSDictionaryM")
                         originSelector:NSSelectorFromString(tmpSetStr)
                          otherSelector:NSSelectorFromString(tmpSafeSetRemoveStr)];
        
    });
    
}

#pragma mark --- implement method

/**
 根据akey 移除 对应的 键值对
 
 @param aKey key
 */
- (void)safeMutable_removeObjectForKey:(id<NSCopying>)aKey {
    if (!aKey) {
        return;
    }
    [self safeMutable_removeObjectForKey:aKey];
}

/**
 将键值对 添加 到 NSMutableDictionary 内
 
 @param anObject 值
 @param aKey 键
 */
- (void)safeMutable_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
    if (!anObject) {
        return;
    }
    if (!aKey) {
        return;
    }
    return [self safeMutable_setObject:anObject forKey:aKey];
}
@end


@implementation NSDictionary (Safe)
+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method originalMethod = class_getClassMethod(self, @selector(dictionaryWithObjects:forKeys:count:));
        Method swizzledMethod = class_getClassMethod(self, @selector(safe_dictionaryWithObjects:forKeys:count:));
        method_exchangeImplementations(originalMethod, swizzledMethod);
        });
}

+ (instancetype)safe_dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt {
    id nObjects[cnt];
    id nKeys[cnt];
    int i=0, j=0;
    for (; i<cnt && j<cnt; i++) {
        if (objects[i] && keys[i]) {
            
            nObjects[j] = objects[i];
            nKeys[j] = keys[i];
            j++;
        }else{
            NSLog(@"字典里面存在了nil数据！！！");
            if(keys[i]){
                if(!objects[i]){
                    NSLog(@"value 为空数据的key:%@",keys[i]);
                }
            }
        }
    }
    return [self safe_dictionaryWithObjects:nObjects forKeys:nKeys count:j];
}

@end
